package com.buxiaoxia.business.service;

import com.buxiaoxia.business.entity.SysRole;
import com.buxiaoxia.business.entity.User;
import com.buxiaoxia.business.repository.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 自定义用户获取方式
 */
@Component
public class CustomUserService implements UserDetailsService {

	@Autowired
	UserDao userDao;

	@Override
	public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
		User user = userDao.findByUserName(s);
		if(user == null){
			throw new UsernameNotFoundException("用户名不存在");
		}
		//用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
		List<SysRole>  sysRoles=userDao.getRoles(user.getId());

		user.setRoles(sysRoles);

		return  user;
	}
}
